package com.compass.mobile.ui.activity

import LogUtil
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.fragment.app.FragmentTransaction
import com.compass.mobile.R
import com.compass.mobile.databinding.ActivityHomePageBinding
import com.compass.mobile.framework.base.BaseVBActivity
import com.compass.mobile.framework.constant.CANCEL_INVITE
import com.compass.mobile.framework.constant.CLOSE_EVENT
import com.compass.mobile.framework.utils.LiveDataBus
import com.compass.mobile.framework.utils.getAction
import com.compass.mobile.models.MessageModel
import com.compass.mobile.ui.fragment.HomePageFragment
import com.google.gson.Gson
import com.google.gson.JsonSyntaxException
import com.google.gson.reflect.TypeToken
import com.netease.nimlib.sdk.NIMClient
import com.netease.nimlib.sdk.Observer
import com.netease.nimlib.sdk.avsignalling.SignallingServiceObserver
import com.netease.nimlib.sdk.avsignalling.constant.SignallingEventType
import com.netease.nimlib.sdk.avsignalling.event.CanceledInviteEvent
import com.netease.nimlib.sdk.avsignalling.event.ChannelCloseEvent
import com.netease.nimlib.sdk.avsignalling.event.ChannelCommonEvent
import com.netease.nimlib.sdk.avsignalling.event.ControlEvent
import com.netease.nimlib.sdk.avsignalling.event.InviteAckEvent
import com.netease.nimlib.sdk.avsignalling.event.InvitedEvent
import com.netease.nimlib.sdk.avsignalling.event.UserJoinEvent
import com.netease.nimlib.sdk.avsignalling.event.UserLeaveEvent
import com.netease.nimlib.sdk.lifecycle.SdkLifecycleObserver
import com.netease.nimlib.sdk.msg.MsgServiceObserve
import toJson


/**
 * Description： navigation Main activity
 * Date:2024/5/9 19:29
 */
class HomePageActivity : BaseVBActivity<ActivityHomePageBinding>() {

    var tag = "VideoCall:===onlineObserver"

    companion object {
        fun start(context: Context) {
            val intent = Intent(context, HomePageActivity::class.java)
            context.startActivity(intent)
        }
    }

    override fun initView(savedInstanceState: Bundle?) {
//        mBinding.topView.setPatientViewVisible(true)
        val fragmentTransaction: FragmentTransaction = supportFragmentManager.beginTransaction()
        fragmentTransaction.replace(R.id.fragmentContainer,HomePageFragment() )
        fragmentTransaction.commit()

    }

    fun setDefaultPatientView(){
        mBinding.topView.setDefaultPatientInfo()
    }

    private var onlineObserver: Observer<ChannelCommonEvent>? = null
    override fun initData() {

        // 在线通知事件观察者
        onlineObserver = Observer<ChannelCommonEvent> { event: ChannelCommonEvent? ->

            when (event?.eventType) {
                SignallingEventType.CLOSE -> {
                    var channelCloseEvent = event as ChannelCloseEvent

                    LiveDataBus.get().with(CLOSE_EVENT).postValue(channelCloseEvent.channelBaseInfo)
                    LogUtil.d(
                        "频道关闭事件 channelCloseEvent==${channelCloseEvent.toJson()}",
                        tag = tag
                    )
                }

                SignallingEventType.UN_KNOW -> {
                    LogUtil.d("未知事件", tag = tag)
                }

                SignallingEventType.JOIN -> {
                    var userJoinEvent = event as UserJoinEvent

                    LogUtil.d(
                        "有人加入频道事件 userJoinEvent==${userJoinEvent.toJson()}",
                        tag = tag
                    )
                }

                SignallingEventType.INVITE -> {
                    var inviteEvent = event as InvitedEvent

                    //收到邀请
                    VideoAnswerActivity.start(this, inviteEvent)
                    LogUtil.d("被邀请事件  inviteEvent==${inviteEvent.toJson()}", tag = tag)
//                    LogUtil.d("被邀请事件  fromAccountId==${inviteEvent.fromAccountId}", tag = tag)
                }

                SignallingEventType.CANCEL_INVITE -> {
                    var canceledInviteEvent = event as CanceledInviteEvent
                    LiveDataBus.get().with(CANCEL_INVITE).postValue(canceledInviteEvent.channelBaseInfo)
                    LogUtil.d(
                        "取消邀请事件 canceledInviteEvent==${canceledInviteEvent.toJson()}",
                        tag = tag
                    )
                }

                SignallingEventType.REJECT, SignallingEventType.ACCEPT -> {
                    var inviteAckEvent = event as InviteAckEvent


                    LogUtil.d(
                        "对方拒绝/接受 邀请事件 inviteAckEvent===${inviteAckEvent.toJson()}",
                        tag = tag
                    )
                }


                SignallingEventType.LEAVE -> {
                    var userLeaveEvent = event as UserLeaveEvent
                    LogUtil.d(
                        "有用户离开频道事件  userLeaveEvent==${userLeaveEvent.toJson()}",
                        tag = tag
                    )
                }

                SignallingEventType.CONTROL -> {
                    var controlEvent = event as ControlEvent
                    LogUtil.d(
                        "自定义控制命令事件  controlEvent==${controlEvent.toJson()}",
                        tag = tag
                    )
                }

                else -> {
                    LogUtil.d("未知事件", tag = tag)
                }
            }

        }
        NIMClient.getService(SignallingServiceObserver::class.java)
            .observeOnlineNotification(onlineObserver, true)
        initCustomNotification()

    }

    /**
     * 注册云信自定义通知
     */
   private fun initCustomNotification() {
        NIMClient.getService(MsgServiceObserve::class.java).observeCustomNotification({
            val type = object : TypeToken<MessageModel>() {}.type
            try {
                val messageModel: MessageModel = Gson().fromJson(it.content, type)
                messageModel.messageType?.let { type->
                    LiveDataBus.get().with(getAction(type)).postValue(messageModel.attach)
                }
            } catch (e: JsonSyntaxException) {

            }

            LogUtil.d("消息通知===${it.toJson()}")


        }, true)

    }

}
